package com.bsoft.apiservice.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.druid.util.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Tools {
    public static String splitStr1 = "||^*||";// 字符串分隔符号
    public static String splitStr2 = "\\|\\|\\^\\*\\|\\|";// 字符串分隔解析符号
    private static Tools DataTools;

    /**
     * 日期转化
     *
     * @param as_date
     * @param al
     * @return
     */
    public static Date ConvertAsDate(String as_date, int al) {
        Date ldt = null;
        try {
            SimpleDateFormat sdf = null;
            if (al != 3)
                sdf = new SimpleDateFormat("yyyy-MM-dd");
            else
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ldt = sdf.parse(as_date);
        } catch (Exception e) {
            if (al == 0) {
                Date date = new Date();
                ldt = date;
            } else
                ldt = null;
        }
        return ldt;
    }

    public static String ConvertDate(Date as_date, int al) {
        Date ldt = null;
        try {
            SimpleDateFormat sdf = null;
            if (al != 3)
                sdf = new SimpleDateFormat("yyyy-MM-dd");
            else
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(as_date);
        } catch (Exception e) {

        }
        return "";
    }
    public static String removeAllNonAlphaNumeric(String s) {
        if (s == null) {
            return null;
        }
        return s.replaceAll("[^0-9]", "");
    }
    public static String escapeExprSpecialWord(String keyword) {
        if (StringUtils.isEmpty(keyword)) {
            String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key);
                }
            }
        }
        return keyword;
    }



    /**
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (str == null)
            return false;
        if (str.trim().equals(""))
            return false;
        Pattern pattern = Pattern.compile("^-?\\d+$"); // 整数
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches())
            return true;
        pattern = Pattern.compile("^(-?\\d+)(\\.\\d+)?$"); // 浮点数
        isNum = pattern.matcher(str);
        if (isNum.matches())
            return true;
        return false;
    }

    /**
     * 字符转换为数值
     *
     * @param str
     * @return
     */
    public static double parsedouble(String str) {
        double ld_num = 0.00;
        if (Tools.isNumeric(str)) {
            ld_num = Double.parseDouble(str);
        }
        return ld_num;

    }

    public static String getAbsoluteFilePath(String FilePath) {
        // 数据库连接
        String sFilePath = "";
        try {
            String sClassdir = Tools.class.getResource("").getPath();
            sClassdir = sClassdir.substring(0,
                    sClassdir.lastIndexOf("classes") + 8);
            sClassdir = new File(sClassdir).getParent();
            sClassdir = URLDecoder.decode(sClassdir, "utf-8");

            sFilePath = sClassdir + "/" + FilePath;

        } catch (Exception e) {

        }
        return sFilePath;
    }

    /**
     * 数字转化为大写
     *
     * @param n
     * @return
     */
    public static String digitUppercase(double n) {
        String fraction[] = { "角", "分" };
        String digit[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
        String unit[][] = { { "元", "万", "亿" }, { "", "拾", "佰", "仟" } };
        String head = n < 0 ? "负" : "";
        n = Math.abs(n);
        String s = "";
        for (int i = 0; i < fraction.length; i++) {
            s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i])
                    .replaceAll("(零.)+", "");
        }
        if (s.length() < 1) {
            s = "整";
        }
        int integerPart = (int) Math.floor(n);
        for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
            String p = "";
            for (int j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[integerPart % 10] + unit[1][j] + p;
                integerPart = integerPart / 10;
            }
            s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i]
                    + s;
        }
        return head
                + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "")
                .replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
    }

    /***************************************************************************
     * repeat - 通过源字符串重复生成N次组成新的字符串。
     *
     * @param src
     *            - 源字符串 例如: 空格(" "), 星号("*"), "浙江" 等等...
     * @param num
     *            - 重复生成次数
     * @return 返回已生成的重复字符串
     * @version
     **************************************************************************/
    public static String repeat(String src, int num) {
        StringBuffer s = new StringBuffer();
        for (int i = 0; i < num; i++)
            s.append(src);
        return s.toString();
    }

    /**
     * JAVA截取字符串右侧指定长度的字符串
     *
     * @param input
     *            输入字符串
     * @param count
     *            截取长度
     * @return 截取字符串
     */
    public static String right(String input, int count) {
        if (input == null)
            input = "";
        count = (count > input.length()) ? input.length() : count;
        return input.substring(input.length() - count, input.length());
    }

    /** * 两个时间之间的天数 */
    public static long getDays(String date1, String date2) {
        if (date1 == null || date1.equals(""))
            return 0;
        if (date2 == null || date2.equals(""))
            return 0;
        // 转换为标准时间
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date = null;
        java.util.Date mydate = null;
        try {
            date = myFormatter.parse(date1);
            mydate = myFormatter.parse(date2);
        } catch (Exception e) {
        }
        long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        return Math.abs(day);
    }

    /** * 两个时间之间的天数 */
    public static long getDays(Date date1, Date date2) {
        if (date1 == null)
            return 0;
        if (date2 == null)
            return 0;
        long day = (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000);
        return Math.abs(day);
    }

    public static int getCharacterPosition(String string, String as_find, int n) {
        // 这里是获取as_find的位置
        int mIdx = 0;
        int postion = 0;
        int findlen = as_find.length();
        postion = string.indexOf(as_find, postion);
        while (postion >= 0) {
            mIdx++;

            if (mIdx == n) {

                break;

            }
            postion = string.indexOf(as_find, postion + 1);
        }
        return postion;
    }

    /**
     * * 获取指定日期是星期几
     *
     * 参数为null时表示获取当前日期是星期几
     *
     * @param date
     *
     * @return
     *
     */

    public static String getWeekOfDate(Date date) {

        String[] weekOfDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };

        Calendar calendar = Calendar.getInstance();

        if (date != null) {

            calendar.setTime(date);
        }

        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {

            w = 0;
        }

        return weekOfDays[w];
    }

    public static int daysNumber(Date date) {
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return w;
    }

    public static String Mid(String aStr, int pos1, int alen) {
        if (aStr == null)
            aStr = "";
        return aStr.substring(pos1 - 1, pos1 + alen - 1);
    }

    public static String Mid(String aStr, int pos1) {
        if (aStr == null)
            aStr = "";
        return aStr.substring(pos1 - 1, aStr.length());
    }

    public static int Pos(String aStr, String afind) {
        return aStr.indexOf(afind) + 1;
    }

    public static Date RelativeDate(Date adate, int aday) {
        return new Date(adate.getTime() + (aday * 24 * 60 * 60 * 1000L));
    }


    public static ArrayList<String> ReadFileLine(String as_filename, String encoding)
            throws IOException {
        ArrayList<String> lArraryList = new ArrayList<String>();
        String fileContent = "";
        File objFile;// 文件对象
        objFile = new File(as_filename);// 创建文件对象
        if (objFile.exists()) {

            // 读文件内容
            InputStreamReader read = new InputStreamReader(new FileInputStream(
                    objFile), encoding);
            BufferedReader reader = new BufferedReader(read);
            String line = "";
            line = reader.readLine();
            while (line != null) {
                lArraryList.add(line);
                line = reader.readLine();

            }
            // 关闭读文件对象
            read.close();
            return lArraryList;
        } else {// 文件不存在

            return lArraryList;
        }
    }



    /**
     * 求Map<K,V>中Value(值)的最小值
     *
     * @param map
     * @return
     */



    public static Object getMinValue(Map<String, Integer> map) {
        if (map == null)
            return null;
        Collection<Integer> c = map.values();
        Object[] obj = c.toArray();
        Arrays.sort(obj);
        return obj[0];
    }
    /**
     * 求Map<K,V>中Value(值)的最大值
     *
     * @param map
     * @return
     */
    public static Object getMaxValue(Map<String, Integer> map) {
        if (map == null)
            return null;
        int length =map.size();
        Collection<Integer> c = map.values();
        Object[] obj = c.toArray();
        Arrays.sort(obj);
        return obj[length-1];
    }

    public static int countMaximum(int maxvalue) {
        maxvalue = (int) (maxvalue + Math.ceil(maxvalue*0.2));
        maxvalue = maxvalue/100*100+100;
        return maxvalue;
    }
    public static Date TStrToDate(String dtFormat) {
        if (dtFormat == null)
            return null;
        try {
            String sdtFormat=dtFormat;
            dtFormat = dtFormat.replaceAll(Tools.escapeExprSpecialWord("-"), "");
            dtFormat = dtFormat.replaceAll(Tools.escapeExprSpecialWord(":"), "");
            if (dtFormat.length() == 8) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
                return dateFormat.parse(dtFormat);
            } else if (dtFormat.length() >= 15) {
                dtFormat = dtFormat.substring(0, 15);
                dtFormat = dtFormat.replaceAll("T", " ");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HHmmss");
                return dateFormat.parse(dtFormat);
            } else {
                return fmtStrToDate(sdtFormat);
            }
        } catch (Exception e) {
            logger.error("出错", e);
            return null;
        }
    }
    private static final Logger logger = LoggerFactory.getLogger(Tools.class);
    public static Date fmtStrToDate(String dtFormat) {
        if (dtFormat == null)
            return null;
        try {
            if(dtFormat.length()>19)
            {
                dtFormat = dtFormat.substring(0,19);
            }
            if (dtFormat.length() == 9 || dtFormat.length() == 8) {
                String[] dateStr = dtFormat.split("-");
                dtFormat = dateStr[0] + (dateStr[1].length() == 1 ? "-0" : "-")
                        + dateStr[1] + (dateStr[2].length() == 1 ? "-0" : "-")
                        + dateStr[2];
            }
            if(dtFormat.length() != 10 && dtFormat.length() != 19 && dtFormat.indexOf(" ")>0){
                String[] dateStr1 = dtFormat.split(" ");
                String[] dateStr =dateStr1[0].split("-");
                String[] dateStr_mhs =dateStr1[1].split(":");
                dtFormat = dateStr[0] + (dateStr[1].length() == 1 ? "-0" : "-")
                        + dateStr[1] + (dateStr[2].length() == 1 ? "-0" : "-")
                        + dateStr[2]+" "
                        +(dateStr_mhs[0].length() == 1 ? "0" : "")+dateStr_mhs[0]
                        +(dateStr_mhs[1].length() == 1 ? ":0" : ":")+dateStr_mhs[1]
                        +(dateStr_mhs[2].length() == 1 ? ":0" : ":")+dateStr_mhs[2];
            }
//			if(dtFormat.length() == 17 || dtFormat.length() == 18){
//				String[] dateStr1 = dtFormat.split(" ");
//				String[] dateStr =dateStr1[0].split("-");
//				dtFormat = dateStr[0] + (dateStr[1].length() == 1 ? "-0" : "-")
//				+ dateStr[1] + (dateStr[2].length() == 1 ? "-0" : "-")
//				+ dateStr[2]+" "+dateStr1[1];
//			}
            if (dtFormat.length() != 10 & dtFormat.length() != 19)
                return null;
            if (dtFormat.length() == 10)
                dtFormat = dtFormat + " 00:00:00";
            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            return dateFormat.parse(dtFormat);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static  String doKsdm(String arg)
    {
        if(StringUtils.isEmpty(arg))
        {
            return "";
        }
        if(arg.indexOf("_")>=0)
        {
            String ksdm[]= arg.split(Tools.escapeExprSpecialWord("_"));
            return ksdm[1];

        }
        else
        {
            return arg;
        }
    }


    //转换OBJECT对象转成字符串
    public static String ToString(Object aobject)
    {
        if (aobject==null)
            return "";
        else
            return aobject.toString();
    }

    //转换OBJECT对象成INT
    public static int ToInt(Object aobject)
    {
        if (aobject==null)
            return 0;
        else
            return (int)parsedouble(aobject.toString());
    }

    //根据生日计算年龄
    public static Map<String, Object> ageFormat(Date birthday, Date nowDate) {
        HashMap<String, Object> resBody = new HashMap<String, Object>();
        if (nowDate == null) {
            nowDate = new Date();
        }
        Calendar now = Calendar.getInstance();
        now.setTime(nowDate);
        Calendar birth = Calendar.getInstance();
        birth.setTime(birthday);
        int age = calculateAge(birthday, nowDate);
        if (age >= 1) {
            resBody.put("age", age);
            resBody.put("age_unit", "1");
            resBody.put("age_unit_name", "岁");
        } else{
            int month =getMonths(birthday, now.getTime());
            int day = getPeriod(birthday, nowDate);
            if (month > 0) {
                resBody.put("age", month);
                resBody.put("age_unit", "2");
                resBody.put("age_unit_name", "月");
            } else {
                if (day >= 3) {
                    resBody.put("age", day);
                    resBody.put("age_unit", "3");
                    resBody.put("age_unit_name", "天");
                } else {
                    int hour = now.get(Calendar.HOUR_OF_DAY)
                            - birth.get(Calendar.HOUR_OF_DAY);
                    resBody.put("age", hour);
                    resBody.put("age_unit", "4");
                    resBody.put("age_unit_name", "小时");
                }
            }
        }
        return resBody;
    }
    /**
     * 计算年龄（周岁）。
     *
     * @param birthday
     *            出生日期。
     * @param calculateDate
     *            计算日。
     * @return
     */
    public static int calculateAge(Date birthday, Date calculateDate) {
        Calendar c = Calendar.getInstance();
        if (calculateDate != null) {
            c.setTime(calculateDate);
        }
        Calendar birth = Calendar.getInstance();
        birth.setTime(birthday);
        int age = c.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
        c.set(Calendar.YEAR, birth.get(Calendar.YEAR));
        if (dateCompare(c.getTime(), birth.getTime()) < 0) {
            return age - 1;
        }
        return age;
    }
    /**
     * 计算两个日期之间的天数，参数null表示当前日期。
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int getPeriod(Date date1, Date date2) {
        if (date1 == null && date2 == null) {
            return 0;
        }
        if (date1 != null && date2 != null && date1.compareTo(date2) == 0) {
            return 0;
        }
        Calendar begin = Calendar.getInstance();
        if (date1 != null) {
            begin.setTime(date1);
        }
        Calendar end = Calendar.getInstance();
        if (date2 != null) {
            end.setTime(date2);
        }
        if (begin.after(end)) {
            Calendar temp = end;
            end = begin;
            begin = temp;
        }
        if (end.get(Calendar.YEAR) == begin.get(Calendar.YEAR)) {
            return end.get(Calendar.DAY_OF_YEAR)
                    - begin.get(Calendar.DAY_OF_YEAR);
        }
        int years = end.get(Calendar.YEAR) - begin.get(Calendar.YEAR);
        int days = begin.getActualMaximum(Calendar.DAY_OF_YEAR)
                - begin.get(Calendar.DAY_OF_YEAR);
        for (int i = 0; i < years - 1; i++) {
            begin.add(Calendar.YEAR, 1);
            days += begin.getActualMaximum(Calendar.DAY_OF_YEAR);
        }
        days += end.get(Calendar.DAY_OF_YEAR);
        return days;
    }

    /**
     * 计算两个日期间的月数。
     *
     * @param date1
     *            较早的一个日期
     * @param date2
     *            较晚的一个日期
     * @return 如果前面的日期小于后面的日期将返回-1。
     */
    public static int getMonths(Date date1, Date date2) {
        Calendar beginDate = Calendar.getInstance();
        beginDate.setTime(date1);
        Calendar now = Calendar.getInstance();
        now.setTime(date2);
        if (beginDate.after(now)) {
            return -1;
        }
        int mon = now.get(Calendar.MONTH) - beginDate.get(Calendar.MONTH);
        if (now.get(Calendar.DAY_OF_MONTH) < beginDate
                .get(Calendar.DAY_OF_MONTH)) {
            if (!(now.getActualMaximum(Calendar.DAY_OF_MONTH) == now
                    .get(Calendar.DAY_OF_MONTH))) {
                mon -= 1;
            }
        }
        if (now.get(Calendar.YEAR) == beginDate.get(Calendar.YEAR)) {
            return mon;
        }
        return 12 * (now.get(Calendar.YEAR) - beginDate.get(Calendar.YEAR))
                + mon;
    }/**
     * 比较两个日期的年月日，忽略时分秒。
     *
     * @param d1
     * @param d2
     * @return 如果d1晚于d2返回大于零的值，如果d1等于d2返回0，否则返回一个负值。
     */
    public static int dateCompare(Date d1, Date d2) {
        Calendar c = Calendar.getInstance();
        c.setTime(d1);
        Calendar c2 = Calendar.getInstance();
        c2.set(Calendar.YEAR, c.get(Calendar.YEAR));
        c2.set(Calendar.MONTH, c.get(Calendar.MONTH));
        c2.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR));
        Date date0 = c2.getTime();

        c.setTime(d2);
        c2.set(Calendar.YEAR, c.get(Calendar.YEAR));
        c2.set(Calendar.MONTH, c.get(Calendar.MONTH));
        c2.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR));
        Date date1 = c2.getTime();

        return date0.compareTo(date1);
    }

    public static void main(String[] args) {
        int maxvalue = 496;
        maxvalue = (int) (maxvalue + Math.ceil(maxvalue*0.2));
        maxvalue = maxvalue/100*100+100;
        System.out.println(maxvalue);
    }


    public static String Conversion(String str) {
        str = str.trim();
        if(str.equals("null")||str==null)
        {
            str = "";
        }
        return str;
    }

}
